<template>
	<view class="main">
		<view class="top">

			<view class="ta" style="margin: 0px 16px;display: flex;justify-content: space-between;align-items: center;">
				<view class="x">问题类型</view>
				<view class="ay" style="display: flex;align-items: center;white-space: nowrap;">
					<u-text :text="wtlxTxt" @click="wtlx()"></u-text>
					<div style="width: 10px;"></div>
					<u-icon name="arrow-down" @click="wtlx()"></u-icon>
					<u-picker :defaultIndex="[getDefaultWtlx()]" :show="wtlxShow" :columns="wtlxList" keyName="name"
						@confirm="changeWtlx" closeOnClickOverlay @close="wtlxCancel()"
						@cancel="wtlxCancel()"></u-picker>
				</view>
			</view>
			<div style="margin: 16px 0px;"><u-line></u-line></div>

			<view class="tb" style="margin: 0px 16px;display: flex;justify-content: space-between;align-items: center;">
				<view class="x">事件紧急程度</view>
				<view class="by" style="display: flex;align-items: center;white-space: nowrap;">
					<u-text :text="fxdjTxt" @click="fxdj()"></u-text>
					<div style="width: 10px;"></div>
					<u-icon name="arrow-down" @click="fxdj()"></u-icon>
					<u-picker :defaultIndex="[getDefaultFxdj()]" :show="fxdjShow" :columns="fxdjList" keyName="name"
						@confirm="changeFxdj" closeOnClickOverlay @close="fxdjCancel()"
						@cancel="fxdjCancel()"></u-picker>
				</view>
			</view>
			<div style="margin: 16px 0px;"><u-line></u-line></div>
			
			<view class="tb" style="margin: 0px 16px;display: flex;justify-content: space-between;align-items: center;">
				<view class="x">事件来源</view>
				<view class="by" style="display: flex;align-items: center;white-space: nowrap;">
					<u-text :text="sjlyTxt" @click="sjly()"></u-text>
					<div style="width: 10px;"></div>
					<u-icon name="arrow-down" @click="sjly()"></u-icon>
					<u-picker :defaultIndex="[getDefaultSjly()]" :show="sjlyShow" :columns="sjlyList" keyName="name"
						@confirm="changeSjly" closeOnClickOverlay @close="sjlyCancel()"
						@cancel="sjlyCancel()"></u-picker>
				</view>
			</view>
			<div style="margin: 16px 0px;"><u-line></u-line></div>

			<view class="tc" style="margin: 0px 16px;">
				<view class="x">发生位置</view>
				<view class="cy" style="margin-top: 16px;">
					<u-input v-model="fswzTxt" style="background-color: #FFF;" readonly @click.native="location">
						<template slot="suffix">
							<u-icon name="map" @click="location"></u-icon>
						</template>
					</u-input>
				</view>
			</view>
			<div style="margin: 16px 0px;"><u-line></u-line></div>

		</view>
		<view class="content">

			<view class="ca" style="margin: 0px 16px;">
				<view class="x">问题描述</view>
				<view class="ae">
					<u--textarea v-model="wtmsTxt" count height="100px" maxlength='2000'
						style="margin-top: 16px;"></u--textarea>
				</view>
			</view>
			<div style="margin: 16px 0px;"><u-line></u-line></div>

			<view class="cb" style="margin: 0px 16px;">
				<view class="x">现场照片</view>
				<view class="be"
					style="border: 1px solid #ceccca;height: 72px;margin-top: 16px;display: flex;border-radius: 4px;">
					<view class="aaa" style="display: flex;" v-for="(item,index) in fileTempList" :key="index">
						<view style="position: relative; margin-top: 8px; margin-left: 8px;">
							<u--image :src="item.url" width="55px" height="55px"></u--image>
							<u-icon name="close" style="position: absolute; top: 2px; right: 2px;"
								@click="removeItem(index)"></u-icon>
						</view>
					</view>
					<u--image :src="upLoadUrl" @click="getFile" v-show="fileTempList.length<5" width="55px"
						height="55px" style="margin-top: 8px;margin-left: 8px;"></u--image>
				</view>
			</view>
		</view>
		<view class="bottom" style="margin: 24px 16px 0px 16px;">
			<u-button @click="submit" text="提 交" color="#FF5000" style="border-radius: 4px;" :loading="loading"></u-button>
			<u-button @click="reset" text="重 置" color="#FF5000" plain
				style="margin-top: 8px;border-radius: 4px;"></u-button>
		</view>
		<div style="height: 16px;"></div>

		<!-- 定位地图图层 -->
		<u-popup :show="showMap" mode="center" @close="showMap=false" :round="10" :safeAreaInsetBottom="false">
			<view class="content" style="width: 90vw;height: 90vh;display: flex;flex-direction: column;">
				<view class="top" style="flex: 1;">
					<view class="map" style="height: 100%;width: 100%;" @touchend="handleTouchEnd">
						<comp-map ref="mainMap" text="1" @mapMounted="onMapMpunted" :showLoc="false"
							:showGol="false"></comp-map>
					</view>
					<u-icon name="map" size="40" color="#FF5000"
						style="position: absolute; bottom: 50%; left: 50%; transform: translate(-50%, 50%);padding-bottom: 148px;z-index: 1000;"></u-icon>
				</view>
				<view class="bottom" style="height: 110px;">
					<view class="atop"
						style="margin:3px;display: flex;justify-content: space-between;align-items: center;height: 50px;">
						<u-icon name="map" style="margin-left: 5px;"></u-icon>
						<u-text :text="tempLocTxt" style="margin-left: 5px;"></u-text>
					</view>
					<div><u-line></u-line></div>
					<view class="bbottom" style="display: flex;height: 45px;">
						<view class="a" @click="upLocation()"
							style="width: 50%;display: flex;justify-content: center;align-items: center;">
							<view style="color: #FF5000;">确 认</view>
						</view>
						<div><u-line direction="col"></u-line></div>
						<view class="b" @click="cancel()"
							style="width: 50%;display: flex;justify-content: center;align-items: center;">
							<view style="color: #909399;">取 消</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import croods from '@/common/croods-1.3.3.js';
	window.croods = croods;
	window.hydra = require('../../../common/wst_hydra-1.0.0.js');


	import coordtransform from 'coordtransform';
	import compMap from "@/components/comp-map/comp-map.vue"
	import {
		getDateDic,
		questionUp,
		uploadFileOfQuestion
	} from '@/common/api.js'
	export default {
		onShow() {
			document.body.style.overflow = 'auto'
			this.getDic(this.fxdjreq)
			this.getDic(this.wtlxreq)
			this.getDic(this.sjlyreq)
			this.getWsToken()
		},
		components: {
			compMap
		},
		data() {
			return {
				upLoadUrl: require("@/static/icons/xjyw/add.png"),
				/* 风险等级 */
				fxdjreq: {
					status: 'Enabled',
					type: 'EVENT_RISK_LEVEL'
				},
				fxdjList: [],
				/* 问题类型 */
				wtlxreq: {
					status: 'Enabled',
					type: 'REPORT_PROBLEM_TYPE'
				},
				wtlxList: [],
				/* 事件来源 */
				sjlyreq: {
					status: 'Enabled',
					type: 'EVENT_SJLY'
				},
				sjlyList: [],

				/* 选择器 */
				wtlxShow: false,
				wtlxStatus: 0,
				fxdjShow: false,
				fxdjStatus: 0,
				sjlyShow: false,
				sjlyStatus: 0,

				/* 请求体参数 */
				wstoken: '',

				wtlxTxt: '请选择',
				fxdjTxt: '请选择',
				sjlyTxt: '请选择',
				fswzTxt: '',
				wtmsTxt: '',
				fileNum: null,

				/* 当前定位经纬度 */
				locLat: null,
				locLng: null,

				/* 图片暂存列表 */
				fileTempList: [],
				/* 图片格式 */
				ijpeg: 'image/jpeg',
				ipng: 'image/png',

				/* 定位地图 */
				showMap: false,

				/* 临时定位变量 */
				tempLat: null,
				tempLng: null,
				tempLocTxt: '',

				/* 天地图Key */
				tk: '033b2d353901718af77cac1bc9a85c6e',
        loading: false,
			}
		},
		methods: {
			/* 字典 */
			getDic(req) {
				getDateDic(req).then(res => {
					if (req.type == 'EVENT_RISK_LEVEL') {
						this.fxdjList = [res]
					} else if (req.type == 'REPORT_PROBLEM_TYPE') {
						this.wtlxList = [res]
					}else if (req.type == 'EVENT_SJLY'){
						this.sjlyList = [res]
					}
				})
			},
			/* 选择器 */
			fxdj() {
				if (this.fxdjTxt == '请选择') {
					this.fxdjTxt = this.fxdjList[0][0].name
				}
				this.fxdjShow = true
			},
			wtlx() {
				if (this.wtlxTxt == '请选择') {
					this.wtlxTxt = this.wtlxList[0][0].name
				}
				this.wtlxShow = true
			},
			sjly() {
				if (this.sjlyTxt == '请选择') {
					this.sjlyTxt = this.sjlyList[0][0].name
				}
				this.sjlyShow = true
			},
			changeWtlx(item) {
				this.wtlxStatus = 1
				let data = item.value
				this.wtlxTxt = data[0].name
				this.wtlxShow = false
			},
			changeFxdj(item) {
				this.fxdjStatus = 1
				let data = item.value
				this.fxdjTxt = data[0].name
				this.fxdjShow = false
			},
			changeSjly(item) {
				this.sjlyStatus = 1
				let data = item.value
				this.sjlyTxt = data[0].name
				this.sjlyShow = false
			},
			fxdjCancel() {
				if (this.fxdjStatus == 0) {
					this.fxdjTxt = '请选择'
				}
				this.fxdjShow = false
			},
			wtlxCancel() {
				if (this.wtlxStatus == 0) {
					this.wtlxTxt = '请选择'
				}
				this.wtlxShow = false
			},
			sjlyCancel() {
				if (this.sjlyStatus == 0) {
					this.sjlyTxt = '请选择'
				}
				this.sjlyShow = false
			},
			getDefaultWtlx() {
				if (this.wtlxList[0]) {
					let index = this.wtlxList[0].findIndex(obj => obj.name === this.wtlxTxt);
					return index
				} else {
					return
				}
			},
			getDefaultFxdj() {
				if (this.fxdjList[0]) {
					let index = this.fxdjList[0].findIndex(obj => obj.name === this.fxdjTxt);
					return index
				} else {
					return
				}
			},
			getDefaultSjly() {
				if (this.sjlyList[0]) {
					let index = this.sjlyList[0].findIndex(obj => obj.name === this.sjlyTxt);
					return index
				} else {
					return
				}
			},
			
			/* 定位 */
			location() {
				let that = this
				if (that.locLng == null && that.locLat == null) {
					window.croods.customPlugin({
						action: 'ServicePermissionPlugin.getLocation',
						params: {
							reason: '获取定位信息',
							required: 1,
							permissionPurpose: '获取位置信息',
							coorType: 'GCJ02'
						},
						success: function(res) {
							let wgs84Coords = coordtransform.gcj02towgs84(res.longitude, res.latitude);
							that.locLng = wgs84Coords[0]
							that.locLat = wgs84Coords[1]
							that.fswzTxt = res.addrStr
							that.tempLocTxt = res.addrStr
							that.showMap = true
						},
						fail: function(msg) {
							that.$u.toast(msg);
						}
					});
				} else {
					that.showMap = true
				}
			},
			/* 地图初始定位 */
			async onMapMpunted() {
				try {
					let temp = {
						lng: this.locLng,
						lat: this.locLat
					}
					if (this.$refs.mainMap != undefined) {
						this.$refs.mainMap.goToLoc(temp);
						this.$refs.mainMap.goToLoc(temp);
					}
				} catch (error) {
					console.error(error);
				}
			},
			/* 位置移动 */
			async handleTouchEnd(event) {
				let that = this
				try {
					if (that.$refs.mainMap != undefined) {
						let temp = that.$refs.mainMap.getCenterLatLng()
						that.tempLat = temp.lat
						that.tempLng = temp.lng

						/* 拼装请求 */
						let loc = {
							lon: temp.lng,
							lat: temp.lat,
							ver: 1
						}
						const url = "https://api.tianditu.gov.cn/geocoder"
						const data = {
							postStr: JSON.stringify(loc),
							type: 'geocode',
							tk: that.tk
						}
						uni.request({
							url: url,
							data: data,
							method: 'GET',
							success: (res) => {
								const temp = res.data.result
								that.tempLocTxt = temp.formatted_address
							},
							fail: (err) => {
								console.log(err);
							}
						});
					}
				} catch (e) {
					console.log(e);
				}
			},
			/* 定位修改 */
			upLocation() {
				this.locLng = this.tempLng == null ? this.locLng : this.tempLng
				this.locLat = this.tempLat == null ? this.locLat : this.tempLat
				this.fswzTxt = this.tempLocTxt == '' ? this.fswzTxt : this.tempLocTxt
				this.showMap = false
			},
			/* 定位取消 */
			cancel() {
				this.tempLat = this.locLat
				this.tempLng = this.locLng
				this.tempLocTxt = this.fswzTxt
				this.showMap = false
			},
			/* 图片上传 */
			async getWsToken() {
				let that = this
				window.croods.customPlugin({
					action: "UserPlugin.login",
					params: {},
					success: function(res) {
						that.wstoken = res.token
					},
					fail: function(msg) {
						console.log(msg);
					}
				});
			},
			getFile() {
				let that = this
				window.croods.customPlugin({
					action: 'ServicePermissionPlugin.uploadMaterial',
					params: {
						reason: "获取相机、文件权限",
						imgCount: "1",
						uploadTitle: "请选择上传方式",
						uploadType: "4",
					},
					success: function(res) {
						let tfile = res.files[0]
						if (res.flag) {
							let temp = tfile.file.replace(/[\r\n]/g, "")
							let url = 'data:' + tfile.type + ';base64,' + temp
							tfile.url = url
							that.fileTempList.push(tfile)
						} else {
							that.$u.toast('格式错误，上传失败');
						}
					},
					fail: function(msg) {
						if (msg != null || msg != undefined) {
							that.$u.toast(msg);
						} else {
							that.$u.toast('照片上传失败');
						}
					}
				});
			},
			removeItem(index) {
				this.fileTempList.splice(index, 1);
			},
			async getIds() {
				let that = this
				let fj = '';
				/* 皖事通令牌 */
				if (that.wstoken == '') {
					that.$u.toast('获取用户信息失败，请刷新界面或重新登录')
					return
				}
				let promises = that.fileTempList.map(async item => {
					let temp = {
						wstoken: that.wstoken,
						bizType: "app",
						file: item.file,
						fileName: item.name,
						fileType: item.type
					}
					let res = await uploadFileOfQuestion(temp);
					if (res != undefined || res != null) {
						fj += res.id + ';'
					}
				})
				await Promise.all(promises);
				return fj;
			},

			/* 重置 */
			reset() {
        if(this.loading) {
          return
        }
				this.wtlxTxt = '请选择'
				this.fxdjTxt = '请选择'
				this.sjlyTxt = '请选择'
				this.fswzTxt = ''
				this.wtmsTxt = ''
				this.fileNum = null
				this.locLat = null
				this.locLng = null
				this.fileTempList = []
			},

			/* 提交 */
			async submit() {
        if(this.loading) {
          return
        }
				let that = this

				/* 现场照片附件 */
				if (that.fileTempList.length == 0) {
					that.$u.toast('现场照片未上传')
					return
				}
				let fj = await that.getIds()
				that.fileNum = fj.slice(0, -1)

				/* 问题类型 */
				if (that.wtlxTxt == '请选择' || that.wtlxTxt == '') {
					that.$u.toast('请选择问题类型')
					return
				}
				let wtlxCode = ''
				let temps = that.wtlxList[0].find(item => item.name == that.wtlxTxt)
				if (temps) {
					wtlxCode = temps.code
				}

				/* 风险等级 */
				if (that.fxdjTxt == '请选择' || that.fxdjTxt == '') {
					that.$u.toast('请选择风险等级')
					return
				}
				let fxdjCode = ''
				let temp = that.fxdjList[0].find(item => item.name == that.fxdjTxt)
				if (temp) {
					fxdjCode = temp.code
				}
				
				/* 事件来源 */
				if (that.sjlyTxt == '请选择' || that.sjlyTxt == '') {
					that.$u.toast('请选择事件来源')
					return
				}
				let sjlyCode = ''
				let tempz = that.sjlyList[0].find(item => item.name == that.sjlyTxt)
				if (tempz) {
					sjlyCode = tempz.code
				}

				/* 发生位置 */
				if (that.fswzTxt == '') {
					that.$u.toast('获取发生位置失败，请通过地图重新获取')
					return
				}
				if (that.locLat == null || that.locLng == null) {
					that.$u.toast('获取坐标失败，请通过地图重新获取')
					return
				}

				/* 问题描述 */
				if (that.wtmsTxt.trim() == '') {
					that.$u.toast('请填写问题描述')
					return
				}

				/* 皖事通令牌 */
				if (that.wstoken == '') {
					that.$u.toast('获取用户信息失败，请刷新界面或重新登录')
					return
				}

				let req = {
					wstoken: that.wstoken,
					wtlx: wtlxCode,
					fxdj: fxdjCode,
					sjly: sjlyCode,
					sjwz: that.fswzTxt,
					jd: that.locLng,
					wd: that.locLat,
					sjms: that.wtmsTxt,
					fjdz: that.fileNum
				}
				
        this.loading = true
				questionUp(req).then(res => {
					if (res.status || res.status == 'true') {
						that.$u.toast('提交成功');
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							});
						}, 1000);
					} else {
						that.$u.toast(res.code);
					}
				}).finally(() => {
          this.loading = false
        })
			}
		},
		mounted() {
			this.getWsToken()
		}
	}
</script>

<style scoped>
	.main {
		margin-top: 16px;
		background-color: #FAFAFA;
	}

	.x {
		font-size: 14px;
		color: #999999;
		font-family: 'PingFang SC';
	}
</style>